var FormWizard = function () {


    return {
        //main function to initiate the module
        init: function () {
            if (!jQuery().bootstrapWizard) {
                return;
            }

            function format(state) {
                if (!state.id) return state.text; // optgroup
                return "<img class='flag' src='assets/img/flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
            }

            var form = $('#submit_form');
            var error = $('.alert-error', form);
            var success = $('.alert-success', form);

            form.validate({
                doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
                errorElement: 'span', //default input error message container
                errorClass: 'validate-inline', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                rules: {
                    //account
                    username: {
                        required: true
                    },
                    tel: {
                        minlength: 11,
                        required: true,
                        number: true,
                        maxlength: 18,
                        min:0
                    },
                    age:{
                        required: true,
                        number: true,
                        minlength:1,
                        maxlength:2,
                        min:1
                    },
                    addressseachdistrict:{
                        required: true,
                        min:1
                    },
                    userMessage:{
                        required:true
                    },
                    note:{
                        required:true
                    }
                },

                messages: { // custom messages for radio buttons and checkboxes
                    username:{
                        required: "请输入顾客姓名"
                    },
                    age:{
                        required: "请输入顾客年龄",
                        number: "必须为数字",
                        minlength:"最小长度为1",
                        maxlength:"最大长度为2",
                        min:"最小年龄1"
                    },
                    tel:{
                        required:"请输入顾客电话",
                        number:"必须为数字",
                        minlength:"联系电话必须为11位",
                        maxlength:"联系电话不得大于18位",
                        min:"不能是负数"
                    },
                    addressseachdistrict:{
                        required:"请选择地区",
                        min:"请选择详细地址"
                    },
                    userMessage:{
                        required:"请填写顾客留言"
                    },
                    note:{
                        required:"请填写备注"
                    }

                },

                errorPlacement: function (error, element) { // render error placement for each input type
                    if (element.attr("name") == "gender") { // for uniform radio buttons, insert the after the given container
                        error.addClass("no-left-padding").insertAfter("#form_gender_error");
                    } else if (element.attr("name") == "payment[]") { // for uniform radio buttons, insert the after the given container
                        error.addClass("no-left-padding").insertAfter("#form_payment_error");
                    } else {
                        error.insertAfter(element); // for other inputs, just perform default behavoir
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit
                    success.hide();
                    error.show();
                    App.scrollTo(error, -200);
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.help-inline').removeClass('ok'); // display OK icon
                    $(element)
                        .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change dony by hightlight
                    $(element)
                        .closest('.control-group').removeClass('error'); // set error class to the control group
                },

                success: function (label) {
                    if (label.attr("for") == "sex") { // for checkboxes and radip buttons, no need to show OK icon
                        label
                            .closest('.control-group').removeClass('error').addClass('success');
                        label.remove(); // remove error label here
                    } else { // display success icon for other inputs
                        label
                            .addClass('valid ok') // mark the current input as valid and display OK icon
                            .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
                    }
                },

                submitHandler: function (form) {
                    success.show();
                    error.hide();
                    //add here some ajax code to submit your form or just call form.submit() if you want to submit the form without ajax
                }

            });

            var displayConfirm = function() {
                $('.display-value', form).each(function(){
                    var input = $('[name="'+$(this).attr("data-display")+'"]', form);
                    if (input.is(":text") || input.is("textarea")|| input.attr("type")=="number") {
                        $(this).html(input.val());
                    }else if($(this).attr("data-display") == 'sex'){
                        var sex=$("input[name='sex']:checked").val();
                        if(sex==1){
                            $(this).html('女');
                        }else if(sex==0){
                            $(this).html('男');
                        }
                    }else if ($(this).attr("data-display") == 'address') {
                        var address = [];
                        $('[name^="address"]').each(function(){
                            address.push($(this).find("option:selected").text());
                        });
                        $(this).html(address.join("-->"));
                    }else if($(this).attr("data-display") == 'proTable'){
                        var projects = [];
                        $("#proTable>tbody>tr").each(function(){
                            projects.push($(this).children("td").first().text());
                        });
                        $(this).html(projects.join(","));
                    }else if($(this).attr("data-display") == 'hospitalTable'){
                        var hospitals = [];
                        $("#hospitalTable>tbody>tr").each(function(){
                            var hospital=$(this).children("td").eq(1).text();
                            var projects=$(this).children("td").find("input[id^='select2_']").select2("val");
                            console.info('hospital---',hospital);
                            console.info('projects---',projects);
                            hospitals.push(hospital+'('+projects+')');
                        });
                        $(this).html(hospitals.join(","));
                    }
                });
            }

            // default form wizard
            $('#form_wizard_1').bootstrapWizard({
                'nextSelector': '.button-next',
                'previousSelector': '.button-previous',
                onTabClick: function (tab, navigation, index) {
                    alert('on tab click disabled');
                    return false;
                },
                onNext: function (tab, navigation, index) {

                    success.hide();
                    error.hide();

                    if (form.valid() == false) {
                        return false;
                    }

                    var total = navigation.find('li').length;
                    var current = index + 1;
                    // set wizard title
                    $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                    // set done steps
                    jQuery('li', $('#form_wizard_1')).removeClass("done");
                    var li_list = navigation.find('li');
                    for (var i = 0; i < index; i++) {
                        jQuery(li_list[i]).addClass("done");
                    }
                    if (current == 1) {
                        $('#form_wizard_1').find('.button-previous').hide();
                    } else {
                        $('#form_wizard_1').find('.button-previous').show();
                    }
                    if (current == 2) {
                        $('#form_wizard_1').find('.button-next').html("保存订单并分配医院");
                    }else{
                        $('#form_wizard_1').find('.button-next').html("下一步");
                    }
                    if(current == 3){
                        var order=getOrderParam();
                        console.info($("#submit_form").serialize());
                        console.info($("#submit_form").serializeArray());
                        console.info(JSON.stringify($("#submit_form").serializeArray()));
                        //TODO 保存订单的时候修改过来
                        getData("POST","saveOrder",false,order,null,null,"callbcakSaveOrder");
                        //callbcakSaveOrder(1);
                    }
                    if(current == 4){
                        //TODO 获取选择医院包含的项目，如若有空则不准许进入下一步
                        if(!validHospitalProjectIds()){
                            alert("医院合作项目不能为空");
                            return false;
                        }else{
                            //进入下一步
                        }

                    }
                    if (current >= total) {
                        $('#form_wizard_1').find('.button-next').hide();
                        $('#form_wizard_1').find('.button-submit').show();
                        displayConfirm();
                    } else {
                        $('#form_wizard_1').find('.button-next').show();
                        $('#form_wizard_1').find('.button-submit').hide();
                    }
                    App.scrollTo($('.page-title'));
                },
                onPrevious: function (tab, navigation, index) {
                    success.hide();
                    error.hide();

                    var total = navigation.find('li').length;
                    var current = index + 1;
                    // set wizard title
                    $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                    // set done steps
                    jQuery('li', $('#form_wizard_1')).removeClass("done");
                    var li_list = navigation.find('li');
                    for (var i = 0; i < index; i++) {
                        jQuery(li_list[i]).addClass("done");
                    }
                    console.info('current--------'+current);
                    if (current == 1) {
                        $('#form_wizard_1').find('.button-previous').hide();
                    } else {
                        $('#form_wizard_1').find('.button-previous').show();
                    }
                    if (current == 2) {
                        $('#form_wizard_1').find('.button-next').html("保存订单并分配医院");
                    }else{
                        $('#form_wizard_1').find('.button-next').html("下一步");
                    }

                    if (current >= total) {
                        $('#form_wizard_1').find('.button-next').hide();
                        $('#form_wizard_1').find('.button-submit').show();
                    } else {
                        $('#form_wizard_1').find('.button-next').show();
                        $('#form_wizard_1').find('.button-submit').hide();
                    }
                    App.scrollTo($('.page-title'));
                },
                onTabShow: function (tab, navigation, index) {
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    var $percent = (current / total) * 100;
                    $('#form_wizard_1').find('.bar').css({
                        width: $percent + '%'
                    });
                }
            });

            $('#form_wizard_1').find('.button-previous').hide();
            $('#form_wizard_1 .button-submit').click(function () {
                alert('Finished! Hope you like it :)');
                var orderId=orderId;
                var hospitalProjectArr=getHospitalProjectArr();
                for(var i=0;i<hospitalProjectArr.length;i++){
                    var project=hospitalProjectArr[i];
                    console.info('project.id---',project.id.substr(('select2_').length));
                    console.info('project.name---',project.name);
                    var minmax=getMinMaxCost(project.name);
                    var mincost=minmax.min;
                    var maxcost=minmax.max;
                    console.info('minmax---',minmax);
                    //TODO 获取订单ID和选择医院的项目ID,获取最高最低消费金额，进行保存
                    getData("POST","saveHospitalProject",false,"orderId="+orderId+"&hospitalProjectId="+project.id.substr(('select2_').length)+"&expectCostMin="+mincost+"&expectCostMax="+maxcost,null,null,"callbcakSaveHospitalProject");

                }
            }).hide();
        }

    };

}();
function getMinMaxCost(projectname){
    console.info('getMinMaxCost---',customer_project_rr);
    for(var i=0;i<customer_project_rr.length;i++){
        var cpr=customer_project_rr[i];
        if(cpr.name==projectname){
            return cpr;
        }
    }
}
function getHospitalProjectArr(){
    var hospitalProjectArr=new Array();
    $("input[id^='select2_']").each(function(){
        console.info('select2----'+$(this).select2("val")+"----id---"+$(this).attr('id'));
        var select2=new Object();
        select2.id=$(this).attr('id');
        select2.name=$(this).select2("val");
        hospitalProjectArr.push(select2);
    });
    return hospitalProjectArr;
}
function getOrderParam(){
    var userName=$("#username").val();
    var userAge=$("#age").val();
    var userPhone=$("#tel").val();
    var userCity=$("#seachdistrict option:selected").val();
    var userSex=$('input:radio[name=sex]:checked').val();
    var note =$("#note").val();
    var userMessage=$("#userMessage").val();
    var orderId="";
    var orderNo=null;
    return "id="+orderId+"&orderNo="+orderNo+"&userName="+userName+"&userAge="+userAge
        +"&userPhone="+userPhone+"&userCity="+userCity
        +"&userSex="+userSex+"&note="+note+"&userMessage="+userMessage;
}
var orderId=null;
var orderNo=null;
var customer_project_rr=new Array();//保存 顾客要做的项目
function projectMinMax(name,min,max){ //use constructor
    this.name=name;
    this.min=min;
    this.max=max;
    return this;
}
//保存订单回调函数
function callbcakSaveOrder(cb){
    console.info(cb);
    //TODO 根据返回的数据设置新增订单ID
    orderId=1;//orderId=cb.id;
    orderNo="20150510123456001";//orderNo=cb.orderNo;
    //TODO 保存项目最高以及最低消费
    $("#proTable>tbody>tr").each(function(){
        console.info("----");
        console.info(this);
        var pname=$(this).children("td").eq(0).html();
        console.info(pname);
        var minV=$(this).find("input[id$=min]").val();
        var maxV=$(this).find("input[id$=max]").val();
        var pmm=new projectMinMax(pname,minV,maxV);
        customer_project_rr.push(pmm);
    });
    console.info(customer_project_rr);
}
//保存订单医院项目关系回调函数
function callbcakSaveHospitalProject(cb){
    console.info(cb);
}
function validHospitalProjectIds(){
    var flag=true;
    $("input[id^='select2_']").each(function(){
        console.info('select2----'+$(this).select2("val")+"----id---"+$(this).attr('id'));
        var selectvalues=$(this).select2("val");
        if(selectvalues==null||selectvalues==undefined||selectvalues==""){
            flag=false;
        }
    });
    return flag;
}